package com.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dao.INSERTUserMapper;
import com.entity.Uploadfileto;
import com.entity.Visitors;
import com.entity.ango;
import com.entity.angomen;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import Decoder.BASE64Decoder;

@Controller
@RequestMapping("/UploadAQGOController")
public class UploadAQGOController {
	private final static String CONTENT_TYPE_TEXT_JSON = "text/json";
	@Resource
	INSERTUserMapper iNSERTUserMapper;
	/*
	 * PAD实时上传人脸接口
	 */
	@ResponseBody
	@RequestMapping(value="/UploadAQGOuser",produces = "text/html;charset=UTF-8", method=RequestMethod.POST)
	public String UploadAQGOuser(String Imgbase,String id,String typeuser,String timeuser) {
		String name=null;
		String sex=null;
		String yaddress=null;;
		String ydetailed=null;
		String yphone=null;
		String yid=id;
		String m="1";
		String n="2";
		angomen go = new angomen();
		Map<String, Object> map = new HashMap<String, Object>();
		String msg=null;
		Date data=new Date();
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss"+"01");
        String newData = dateFormat.format(data);
		String str=".jpg";
		String yfilename2="/home/apache-tomcat-7.0.47/webapps/image/sszp/"+newData+str;
		//String yfilename2="C:/100/"+newData+str;
		String yfilename="https://wwl.ycws.cc/image/sszp/"+newData+str;
		if(Imgbase==null||Imgbase==""||id==null||id==""||typeuser==null||typeuser==""){
				msg ="200";
				map.put("state", msg);
				new JSONObject();
				JSONObject json=JSONObject.fromObject(map);
				return json.toString();
			}else {
				
					try {
						if(typeuser.equals(m)){
							Uploadfileto up=iNSERTUserMapper.selecuserid(yid);
							name=up.getYname();
							sex=up.getYsex();
							yaddress=up.getYaddress();
							ydetailed=up.getYdetailed();
							yphone=up.getYphone();
						}else if (typeuser.equals(n)) {
							Visitors vi=iNSERTUserMapper.selecvisitorsid(yid);
							name=vi.getYname();
							sex=vi.getYsex();
							yaddress=vi.getYaddress();
							ydetailed=vi.getYunitdoor();
							yphone=vi.getYphone();
						}
							BASE64Decoder  deone = new BASE64Decoder();
						//解密
						byte [] b = deone.decodeBuffer(Imgbase);
						//转换数据
						for (int i=0;i<b.length;++i){
							if(b[i]<0){
								b[i] +=256;
							}
						}
						OutputStream out = new FileOutputStream(yfilename2);
						out.write(b);
						out.flush();
						out.close();
						

						iNSERTUserMapper.insertuservisitors(yfilename, typeuser,name,sex,yaddress,ydetailed,yphone,yid,timeuser);
					//插入数据	
					msg="1";
					String urlStr="http://120.77.173.150:8070/user/match/upload";//安全GO接口地址
					String jsonone=updownaqgo(yfilename, urlStr);//安全GO接口
					 if (jsonone != null) {
				    	   JsonParser parser = new JsonParser(); // 创建JSON解析器
			               JsonObject object = (JsonObject) parser.parse(jsonone); // 创建JsonObject对象
			               String statemen=object.get("status").getAsString();
			               iNSERTUserMapper.updownango(yfilename,statemen);         
					 }else {
						 iNSERTUserMapper.updownangono(yfilename);
					 }
					 
					} catch (FileNotFoundException e) {
						msg="0";
						
					} catch (IOException e) {
						msg="0";

					}catch (Exception e) {
						msg="0";

					}
					
					map.put("state", msg);
					new JSONObject();
					JSONObject json=JSONObject.fromObject(map);
					return json.toString();
			}
	}
	
	/**
	 * 调用安全Go接口
	 * @param yfilename
	 * @param urlStr
	 * @return
	 */
	public String updownaqgo(String yfilename,String urlStr){
		new JSONObject();
		List<ango> listango=iNSERTUserMapper.selectango(yfilename);//查询存入的数据
		Map<String, Object>map = new HashMap<String, Object>();
		map.put("listone", listango);
		JSONObject json=JSONObject.fromObject(map);
		String jsonstr=json.toString();
		System.out.println(jsonstr);
	        String result = null;
	        HttpPost httpPost = new HttpPost(urlStr);
	        try {
	            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
	            // httpPost.setHeader("Content-Type", "application/json");
	            StringEntity se = new StringEntity(jsonstr, "UTF-8");
	            se.setContentType(CONTENT_TYPE_TEXT_JSON);
	            httpPost.setEntity(se);
	            @SuppressWarnings("resource")
	            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
	            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
	            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

	            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
	            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
	                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据    
	            } else {
	            	return result;
	            }
	        } catch (ConnectTimeoutException e) {
	        	return result;
	        } catch (UnsupportedEncodingException e) {
	        	return result;
	        } catch (IOException e) {
	        	return result;
	        } catch (Exception e) {
	        	return result;
	        }
		
		return result;
	}
	
	/**
	 * 测试
	 * @return
	 */
	public String testOneture(){
		String New ="123456";
		return New;
	}
	
	/*@ResponseBody
	@RequestMapping(value="/Newtestonetrie",produces = "text/html;charset=UTF-8", method=RequestMethod.GET)
	public void Newtestonetrie(){
		List<ango> listango=iNSERTUserMapper.selectangodrawandblank();;//查询存入的数据
		for (int i = 0; i < listango.size(); i++) {
			int in=listango.get(i).getId();
			String NEWs=String.valueOf(in);
			System.out.println(NEWs);
		}
	}*/
	
/*	@ResponseBody
	@RequestMapping(value="/testupdownaqgo",produces = "text/html;charset=UTF-8", method=RequestMethod.GET)
	public void testupdownaqgo(){
		String yfilename="https://wwl.ycws.cc/image/sszp/2017120114202701.jpg";
		String urlStr="http://120.77.173.150:8070/user/match/upload";
		String jsonone=updownaqgo(yfilename, urlStr);//安全GO接口
		 if (jsonone != null) {
			 System.out.println(jsonone);
	    	   JsonParser parser = new JsonParser(); // 创建JSON解析器
               JsonObject object = (JsonObject) parser.parse(jsonone); // 创建JsonObject对象
               String statemen=object.get("status").getAsString();
               iNSERTUserMapper.updownango(yfilename,statemen);         
		 }else {
			 iNSERTUserMapper.updownangono(yfilename);
		}
	}*/
}
